# Copyright 2020-2020 the openage authors. See copying.md for legal info.

"""
Create a manifest file for a modpack
"""

import toml

from ..data_definition import DataDefinition


class ManifestFile(DataDefinition):
    """
    Used for creating a manifest file for a modpack.
    """

    def __init__(self, targetdir, filename):
        super().__init__(targetdir, filename)

        self.hash_values = []
        self.hashing_func = None

    def dump(self):
        """
        Returns the manifest file content in TOML format.
        """

        output_dict = {}

        info_table = {"info": {}}
        # write the hashing algorithm used
        info_table["info"].update({"hash": self.hashing_func})

        output_dict.update(info_table)

        # write the hash values and the relative paths
        # of the items in the exported directory
        hash_values_table = {'hash-values': {}}
        for hash_val, item_path in self.hash_values:
            hash_values_table['hash-values'].update({hash_val: item_path})

        output_dict.update(hash_values_table)

        output_str = "# openage autogenerated modpack integrity check\n\n"
        output_str += toml.dumps(output_dict)

        return output_str

    def add_hash_value(self, hash_val, item_path):
        """
        Add the item path and its hash value to the instances
        hash_values list.

        :param hash_val: the hash value of the item
        :type hash_val: str
        :param item_path: relative path of item to the exported path
        :type item_path: str
        """
        self.hash_values.append((hash_val, item_path,))

    def set_hashing_func(self, hashing_func):
        """
        Add the hashing function used for generating
        hash values for modpack files

        :param hashing_func: Hashing algorithm
        :type hashing_func: str
        """
        self.hashing_func = hashing_func
